package com.aaa.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenUtils {

    private static String secret="cw-a";
    /**
     *     通过jwt生成token令牌
     */
    public static String getToken(Map<String,Object> map){
        //创建head头
        Map<String,Object> head = new HashMap<>();
        head.put("alg", "HS256");
        head.put("typ", "JWT");
        //创建发布时间
        Date date = new Date();
        //创建过期时间
        Calendar expire = Calendar.getInstance();//获取当前时间
        expire.set(Calendar.SECOND,7200);//在当前时间增加7200s
        Date expireTime = expire.getTime();
        String token = JWT.create().withHeader(head)
                .withSubject("JWT测试") //主题
                .withIssuedAt(date) //签发时间
                .withExpiresAt(expireTime) //过期时间
                .withClaim("map", map) //自定义数据
                .sign(Algorithm.HMAC256(secret));//签名
        return token;
    }
    /**
     * 验证token是否合法正确
     */
    public static boolean validateToken(String token){
        Verification require = JWT.require(Algorithm.HMAC256(secret));//获取签名
        try {
            DecodedJWT verify = require.build().verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 获取token中指定的数据
     */
    public static Map<String,Object> getInfo(String token){
        Verification require = JWT.require(Algorithm.HMAC256(secret));//获取签名
        DecodedJWT verify = require.build().verify(token);
        Map<String, Object> map = verify.getClaim("map").asMap();
        return map;
    }
}
